package com.ruoyi.project.wenyanwen.export.service.impl;

import com.ruoyi.common.utils.JsonUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.datasource.DynamicDataSourceContextHolder;
import com.ruoyi.project.wenyanwen.export.mapper.QueryDao;
import com.ruoyi.project.wenyanwen.export.service.QueryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author jackyshi
 */
@Service
public class QueryServiceImpl implements QueryService {

    @Autowired
    QueryDao queryDao;

    @Override
    public List<?> query(String datasource, String tableName, String sql, Class<?> cls, int start, int size) {

        DynamicDataSourceContextHolder.setDataSourceType(datasource);
        try {
            List<Map<String, Object>> list;
            if (StringUtils.isEmpty(sql)) {
                list = queryDao.query(tableName, start, size);
            } else {
                list = queryDao.queryBySql(sql, start, size);
            }
            if (cls == Map.class) {
                return list;
            } else {
                List<String> jsons = new ArrayList<>();
                for (Map<String, Object> map : list) {
                    Map<String, Object> data = new HashMap<>();
                    for (Map.Entry<String, Object> entry : map.entrySet()) {
                        data.put(column2field(entry.getKey()), entry.getValue());
                    }
                    jsons.add(JsonUtil.toJson(data));
                }
                return JsonUtil.toObject(jsons, cls);
            }

        } finally {
            DynamicDataSourceContextHolder.clearDataSourceType();
        }
    }

    private String column2field(String columnName) {

        char[] chs = columnName.toCharArray();
        StringBuffer fieldName = new StringBuffer();
        boolean toUperCase = false;
        for (char ch : chs) {
            if (ch == '_') {
                toUperCase = true;
            } else {
                if (toUperCase) {
                    fieldName.append(String.valueOf(ch).toUpperCase());
                    toUperCase = false;
                } else {
                    fieldName.append(ch);
                }
            }
        }
        return fieldName.toString();
    }

    @Override
    public int count(String datasource, String tableName) {
        DynamicDataSourceContextHolder.setDataSourceType(datasource);
        try {
            return queryDao.count(tableName);
        } finally {
            DynamicDataSourceContextHolder.clearDataSourceType();
        }
    }
}
